package cn.htsyb.synergy.maker.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class ResultSetUtil {
    private final static Logger logger = LoggerFactory.getLogger(ResultSetUtil.class);

    public static <T> T metaToBean(ResultSet entryRS, Class<T> clazz) throws Exception {
        T entry = clazz.getDeclaredConstructor().newInstance();
        ResultSetMetaData metaDataRS = entryRS.getMetaData();

        for (int i = 1; i < metaDataRS.getColumnCount(); i++) {
            String name = metaDataRS.getColumnLabel(i).trim();
            Object value = entryRS.getObject(i);

            //默认情况下，meta中的变量名均是全大写并以“_”分割，为方便阅读这里统一处理成无“_”的小驼峰命名
            name = HumpUtil.convertToSmallHump(name.toLowerCase(), "_");

            try {
                PropertyDescriptor prop = new PropertyDescriptor(name, clazz);
                if (prop != null && prop.getWriteMethod() != null) {
                    prop.getWriteMethod().invoke(entry, value);
                }
            } catch (IntrospectionException e) {
                if(logger.isDebugEnabled()) {
                    logger.debug("字段{}在{}中不存在，值为{},类型为{}", name, clazz, value, value != null ? value.getClass().getName() : "");
                }
            } catch (IllegalArgumentException e) {
                if(logger.isDebugEnabled()) {
                    logger.debug("字段{}与{}中同名属性类型不匹配，值为{},类型为{}", name, clazz, value, value!=null?value.getClass().getName():"");
                }
            }
        }

        return entry;
    }
}
